#include "I2CManager.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <fcntl.h>

#define I2C_FILE  "/dev/i2c-2"


int getI2CFile()
{
	/* Ouverture du fichier en mode lecture et ecriture */
	return open(I2C_FILE, O_RDWR);
}

int write8(int i2CFile, int tenBitAddress, int slaveAddr, char reg, unsigned char value)
{
	char data[2];
	data[0] = 0;
	data[1] = 0;
	/*	ioctl : controle les entree/sortie pour un peripherique particulier
		On specifie si l'adress de l'esclave est sur 10 bit ou pas */
	ioctl(i2CFile, I2C_TENBIT, tenBitAddress);
	/* On specifie le peripherique esclave avec lequel on veut communiquer */
	ioctl(i2CFile, I2C_SLAVE, slaveAddr);

	data[0] = reg;
	data[1] = value;
	
	if( write(i2CFile, &data, 2) > 0 )
		return 1;
			
	return -1;
}

int read8(int i2CFile, int tenBitAddress, int slaveAddr, char reg, unsigned char* val)
{
	ioctl(i2CFile, I2C_TENBIT, tenBitAddress);
	ioctl(i2CFile, I2C_SLAVE, slaveAddr);
	
	if( write(i2CFile, &reg, 1) > 0 )
		if( read(i2CFile, val, 1) > 0 )
			return 1;
		
	return -1;
}

int read16(int i2CFile, int tenBitAddress, int slaveAddr, char reg, uint8_t* val1, uint8_t* val2)
{
	char buffer[2];
	buffer[0] = 0;
	buffer[1] = 0;
	
	if( ioctl(i2CFile, I2C_TENBIT, tenBitAddress) < 0 )
	{
		perror("ioctl I2C_TENBIT");
		return -1;
	}
	if( ioctl(i2CFile, I2C_SLAVE, slaveAddr) < 0 )
	{
		perror("ioctl I2C_SLAVE");
		return -1;
	}
	
	if( write(i2CFile, &reg, 1) < 0 )
	{
		perror("write registre");
		return -1;
	}

	if( read(i2CFile, buffer, 2) < 0 )
	{
		perror("read val");
		return -1;
	}
	
	*val1 = buffer[0];
	*val2 = buffer[1];
	
	return 1;
}
